package com.boarsoft.boar.gateway.rpc;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.common.util.InetUtil;
import com.boarsoft.rpc.bean.RpcRegistry;
import com.boarsoft.rpc.bean.RpcServiceConfig;
import com.boarsoft.rpc.core.RpcContext;
import com.boarsoft.rpc.core.RpcCore;
import com.boarsoft.rpc.listener.RpcListener;

public class GatewayRpcListener implements RpcListener {
	private static final Logger log = LoggerFactory.getLogger(GatewayRpcListener.class);

	@Autowired
	protected RpcContext rpcContext;

	@Override
	public void onRemoveLink(String addr, String reason) {
		// Nothing to do
	}

	@Override
	public void onRegister(RpcRegistry reg) {
		// Nothing to do
	}

	@Override
	public void onDeregister(RpcRegistry reg) {
		// Nothing to do
	}

	@Override
	public void onUpdateRegistry(RpcRegistry rr) {
		String remoteAddr = rr.getKey();
		// 不检查自己的注册表
		if (InetUtil.getAddr().equals(remoteAddr)) {
			return;
		}
		RpcCore rpcCore = RpcCore.getCurrentInstance();
		// 来自远程的serviceMap
		Map<String, RpcServiceConfig> sm = rr.getServiceMap();
		for (String sk : sm.keySet()) {
			log.debug("Found service provider {} -> {}", remoteAddr, sk);
			RpcServiceConfig sc = sm.get(sk);
			rpcCore.putProvider(rr, sc);
		}
	}

	public RpcContext getRpcContext() {
		return rpcContext;
	}

	public void setRpcContext(RpcContext rpcContext) {
		this.rpcContext = rpcContext;
	}
}
